<template>
  <div class="roles">
    <el-card>
      <el-row class="roles-header" type="flex" justify="space-between">
        <el-col>
          <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
              >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
          </el-breadcrumb>
        </el-col>
        <el-button type="primary" @click="editDialogVisible = true"
          >添加角色</el-button
        >
      </el-row>

      <el-table :data="tableData" style="width: 100%" border stripe>
        <el-table-column type="expand" class="expand">
          <template v-slot="data">
            <el-row
              v-for="(item, index) in data.row.children"
              :key="item.id"
              :class="[index == 0 ? 'borderTop' : '', 'first']"
            >
              <!-- 一级标题 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="close(data.row, item)"
                  >{{ item.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级标题 -->
              <el-col :span="19">
                <el-row
                  v-for="(i, index) in item.children"
                  :key="i.id"
                  :class="[index !== 0 ? 'second' : '']"
                >
                  <el-col :span="8">
                    <el-tag type="success" closable @close="close(data.row, i)">
                      {{ i.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>

                  <el-col :span="16">
                    <el-row>
                      <el-tag
                        closable
                        type="warning"
                        v-for="j in i.children"
                        :key="j.id"
                        class="endTag"
                        @close="close(data.row, j)"
                      >
                        {{ j.authName }}
                      </el-tag>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>

        <el-table-column prop="roleName" label="用户名" width="180">
        </el-table-column>
        <el-table-column prop="roleDesc" label="用户岗位" width="180">
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="control">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="edit(control.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeItem(control.row.id)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="settingRights(control.row, 'edit')"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限 -->
    <el-dialog
      title="分配权限"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-tree
        :data="data"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectData"
        :props="defaultProps"
        accordion
        default-expand-all
        ref="treeRef"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加or编辑用户 -->
    <el-dialog
      title="提示"
      :visible.sync="editDialogVisible"
      width="30%"
      :before-close="handleClose"
      @closed='closed'
    >
      <el-form :model="addOrEditArr" label-width="80px">
        <el-form-item label="角色名称" prop="roleName" >
          <el-input type="text" v-model="addOrEditArr.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc" >
          <el-input type="text" v-model="addOrEditArr.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAxiosData">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tableData: [], //列表
      data: [], //添加用户tree 列表
      selectData: [], //分配权限   已选则列表项
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      dialogVisible: false, //是否打开弹窗
      tempId: '', //临时存储编辑的用户id

      editDialogVisible: false, //添加or 编辑
      addOrEditArr: {
        roleName: '',
        roleDesc: '',
      },
      editId: '', //用于区分添加 or  编辑
    }
  },

  created() {
    this.getTableData()
  },
  methods: {
    async getTableData() {
      const { data, meta } = await this.$axios.get('/api/roles')
      if (meta.status == 200) {
        this.tableData = data
        console.log(this.tableData)
      }
    },
    removeItem(id) {
      //删除用户
      this.$confirm('是否确认删除？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(async () => {
          const { meta } = await this.$axios.delete('/api/roles/' + id)
          if (meta.status == 200) {
            this.$message.success('删除成功')
            this.getTableData()
          } else {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {})
    },

    async saveAxiosData() {
      //编辑用户
      let flag = true
      for (let prop in this.addOrEditArr) {
        if (!this.addOrEditArr[prop]) {
          return this.$message.error('未填写完成')
        }
      }
      if (this.editId) {
        const { meta } = await this.$axios.put(`/api/roles/${this.editId}`, {
          ...this.addOrEditArr,
        })
        if (meta.status == 200) {
          this.getTableData()
        } else {
          flag = false
        }
      } else {
        const { meta, data } = await this.$axios.post('/api/roles', {
          ...this.addOrEditArr,
        })
        if (meta.status == 201) {
          this.data = data
        } else {
          flag = false
        }
      }
      if (flag) {
        this.$message.success('成功') 
      } else {
        this.$message.error('失败')
      }
        this.editDialogVisible = false
     
    },
    settingRights(val) {
      //设置权限
      this.selectData = []
      this.dialogVisible = true
      this.tempId = val.id
      this.traverse(val)
      this.getSelectData()
    },
    async getSelectData() {
      //获取分配权限数据
      const { meta, data } = await this.$axios.get('/api/rights/tree')
      if (meta.status == 200) {
        this.data = data
      }
    },
    traverse(val) {
      //递归获取所有子节点
      let trans = (item) => {
        if (!item.children) {
          this.selectData.push(item.id)
        } else {
          for (let prop in item.children) {
            trans(item.children[prop])
          }
        }
      }
      trans(val)
    },
    async close(user, tag) {
      this.$confirm('是否确认删除？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      })
        .then(async () => {
          const { meta, data } = await this.$axios.delete(
            `/api/roles/${user.id}/rights/${tag.id}`
          )
          if (meta.status == 200) {
            this.getTableData
            console.log(data, this.tableData, tag)
          }
          if (meta.status == 200) {
            this.$message.success('删除成功')
            user.children = data
            // this.getTableData()
          } else {
            this.$message.error('删除失败')
          }
        })
        .catch(() => {})
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(() => {
          this.selectData = []
          done()
        })
        .catch(() => {})
    },
    edit(val) {
      //点击编辑按钮
      console.log(val)
      for (let prop in this.addOrEditArr) {
        this.addOrEditArr[prop] = val[prop]
      }
      this.editDialogVisible = true
      console.log(val)
      this.editId = val.id
    },
    async submitData() {
      const temp1 = this.$refs.treeRef.getHalfCheckedKeys()
      const temp2 = this.$refs.treeRef.getCheckedKeys()
      var temp = [...temp1, ...temp2].join(',')
      const { meta, data } = await this.$axios.post(
        `/api/roles/${this.tempId}/rights`,
        { rids: temp }
      )

      console.log(meta, data)
      console.log(this.selectData, this.tempId)

      if (meta.status == 200) {
        this.dialogVisible = false
        this.getTableData()
        console.log(data)
      }
    },
    closed() {
      this.addOrEditArr = {
        roleName: '',
        roleDesc: '',
      }
    },
  },
}
</script>

<style lang="less" scoped>
div.roles {
  .el-card {
    .el-row.roles-header {
      display: flex;
      .el-button {
        height: 40px;
      }
    }
    .el-table {
      .el-row {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        &.borderTop.first {
          border-top: 1px solid #ccc;
        }
        &.first {
          border-bottom: 1px solid #ccc;
          padding-left: 100px;
        }
        .endTag {
          margin: 8px 5px;
        }
        &.second {
          border-top: 1px solid #eee;
        }
        .el-tag {
          margin-right: 5px;
        }
      }
    }
  }
}
</style>
